//
//  PKPlayerManger.m
//  MusicPlayer
//
//  Created by lanou on 15/10/5.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PKPlayerManger.h"
@interface PKPlayerManger ()
// 保存音乐地址的数组
@property (nonatomic, strong) NSArray *musicArray;
@property (nonatomic, assign) NSInteger palayIndex;
@end

@implementation PKPlayerManger
- (instancetype)init{
    self = [super init];
    if (self) {
        _avPlayer = [[AVPlayer alloc] init];
    }
    return self;
}
+ (instancetype)shareManger{
    static PKPlayerManger *manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[PKPlayerManger alloc] init];
    });
    return manger;
}
// 给播放器设置播放的地址数组
- (void)setMangerMusicArray:(NSArray *)array{
    _musicArray = array;
}

- (void)playWithIndex:(NSInteger)index{
    NSURL *musicURL = [NSURL URLWithString:_musicArray[index]];
    _palayIndex = index;
    // 根据创建过来的下标选择数组中的播放地址
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:musicURL];
    // 把播放器的地址替换为新的地址
    [_avPlayer replaceCurrentItemWithPlayerItem:item];
    [_avPlayer play];
}
- (void)nextMusic{
    _palayIndex ++;
    if (_palayIndex == _musicArray.count) {
        _palayIndex = 0;
    }
    // 播放类型为随机播放
    if (_playType == PlayTypeRandom) {
        _palayIndex = arc4random() % _musicArray.count;
    }
    [self playWithIndex:_palayIndex];
}
- (void)beforeMusic{
    _palayIndex --;
    if (_palayIndex < 0) {
        _palayIndex = _musicArray.count - 1;
    }
    // 播放类型为随机播放
    if (_playType == PlayTypeRandom) {
        _palayIndex = arc4random() % _musicArray.count;
    }
    [self playWithIndex:_palayIndex];
}
// 判断当前播放状态，0.0代表停止，1.0代表播放
- (void)playAndPause{
    if (_avPlayer.rate == 0.0) {
        [_avPlayer play];
    }else{
        [_avPlayer pause];
    }
    
}
- (NSUInteger)finishTime{
  CMTime time = _avPlayer.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value / time.timescale;
}
- (NSUInteger)currentTime{
   CMTime time = _avPlayer.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value / time.timescale;
}
- (void)seekToTime:(NSUInteger)time{
    CMTime newTime = _avPlayer.currentTime;
    // 秒 = value / 基数
    newTime.value = newTime.timescale * time;
    [_avPlayer seekToTime:newTime];
    [_avPlayer play];
}
- (void)stop{
    [self seekToTime:0];
    [_avPlayer pause];
}
@end
